package com.example.bianpan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;


@Component
@Slf4j
public class ProcessNodesFactory  implements ApplicationContextAware {

    private LinkedHashMultimap<String,Node> operation2Nodes = LinkedHashMultimap.create();

    private Map<String,Node> name2Node = Maps.newHashMap();

    public Set<Node> get(String operation)
    {
        return  operation2Nodes.get(operation);
    }

    public  void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
        log.info("开始");
        Map<String,Node> beansOfType = applicationContext.getBeansOfType(Node.class);
        beansOfType.values().forEach(node -> {
            String nodeName = node.getNodeName();
            name2Node.put(nodeName,node);
        });

        OperationAndNodes jsonObject = new OperationAndNodes();
        jsonObject.setOperation("ABILITY_CAL");
        var list = new ArrayList<String>();
        list.add("节点1");
        list.add("节点2");
        list.add("节点3");
        jsonObject.setNodeList(list);

        //解析节点编排文件

        List<OperationAndNodes> operationAndNodesList = new ArrayList<OperationAndNodes>();
        operationAndNodesList.add(jsonObject);

        for (OperationAndNodes operationAndNodes: operationAndNodesList){
            for (String nodeName:operationAndNodes.nodeList){
                Node node = name2Node.get(nodeName);
                if(Objects.isNull(node))
                {
                    throw new RuntimeException("[节点工厂]请定义节点："+nodeName);
                }
                operation2Nodes.put(operationAndNodes.operation,node);
            }
        }

        log.info("[节点工厂] 加载完毕，所有编排为：{}",JSON.toJSONString(operation2Nodes.asMap()));



    }

    @Data
    public  static class OperationAndNodes{
        private String operation;
        private List<String> nodeList;
    }



}
